<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { queryAllApi, saveApi, queryByIdApi, updateApi, deleteApi } from "@/api/dept";

const tableData = ref([]);

const dialogName = ref("");

const dialogFormVisible = ref(false);
const formLabelWidth = "100px";

onMounted(() => {
  searchDeptList();
});

const searchDeptList = async () => {
  // const result = await axios.get(`https://m1.apifoxmock.com/m1/6121661-5813298-default/depts`)
  const result = await queryAllApi();
  if (result.code) {
    tableData.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
};
/* 新增部门/修改部门表单数据模型 */
const deptForm = ref({
  name: "",
});

const addDept = () => {
  // 清空对话框中的表单
  deptForm.value = { name: "" };
  // 清空表单中的校验规则
  if (deptRef.value) {
    deptRef.value.resetFields();
  }
  dialogFormVisible.value = true;
  dialogName.value = "新增部门";
};

// 点击确定，新增/修改部门
const saveDept = async () => {
  if (!deptRef.value) return;
  // 对表单进行校验
  deptRef.value.validate(async (valid) => {
    if (valid) {
      // 表单校验通过
      dialogFormVisible.value = false;
      let result = null;
      // 判断修改还是新增
      if (deptForm.value.id) {
        // 修改部门
        result = await updateApi(deptForm.value);
      } else {
        // 新增部门
        // 调用JS中的函数，保存部门到数据库
        result = await saveApi(deptForm.value);
      }

      if (result.code) {
        // 新增成功
        ElMessage.success("保存成功");
        // 重新查询列表数据
        searchDeptList();
      } else {
        ElMessage.error(result.msg);
      }
    } else {
      // 表单校验失败
      ElMessage.error("表单校验失败");
    }
  });
};

// 表单校验相关
const deptRef = ref();
const rules = ref({
  name: [
    { required: true, message: "请输入部门名称", trigger: "blur" },
    {
      min: 2,
      max: 10,
      message: "部门名称长度必须在2-10位之间",
      trigger: "blur",
    },
  ],
});

// 点击编辑按钮
const edit = async (id) => {
  dialogName.value = "编辑部门";
  // 清空表单中的校验规则
  if (deptRef.value) {
    deptRef.value.resetFields();
  }
  dialogFormVisible.value = true;
  // 根据部门id查询部门信息
  const result = await queryByIdApi(id);
  if (result.code) {
    deptForm.value = result.data;
  }
};

// 点击删除按钮
const deleteById = (id) => {
  // 弹出一个确认框
  ElMessageBox.confirm(
    "您确定要删除这条记录吗？",
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
      // 调用方法删除这条数据
      const result = await deleteApi(id)
      if(result.code) {
        // 重新查询列表数据
        searchDeptList()
        ElMessage.success("删除成功")
      } else {
        ElMessage.error(result.msg)
      }
    })
    .catch(() => {
      ElMessage.info("取消删除")
    });
};
</script>

<template>
  <h1>部门管理</h1>
  <br />
  <el-button type="primary" style="float: left" @click="addDept"
    >+ 新增部门</el-button
  >
  <br /><br />

  <!-- table表格 -->
  <el-table :data="tableData" border style="width: 80%">
    <el-table-column type="index" label="序号" align="center" width="180" />
    <el-table-column prop="name" label="部门名称" align="center" width="400" />
    <el-table-column
      prop="updateTime"
      label="最后操作时间"
      align="center"
      width="400px"
    />
    <el-table-column prop="address" label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="edit(scope.row.id)"
          >编辑</el-button
        >
        <el-button type="danger" size="small" @click="deleteById(scope.row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <!-- 新增部门/修改部门对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogName" width="500px">
    <el-form :model="deptForm" :rules="rules" ref="deptRef">
      <el-form-item label="部门名称" :label-width="formLabelWidth" prop="name">
        <el-input
          v-model="deptForm.name"
          autocomplete="off"
          placeholder="请输入部门名称，长度为2-10位"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDept"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>
